import { throttle } from 'lodash'
import dayjs from 'dayjs'

import { reqActionTime } from "./spotMarketReq";
import { getSaveAllDayTradeInfo, getSaveOneTypeTradeInfo } from '@src/spotMarketPrivateData/mediumAndLongTerm/tradeInfo';
import { createGetRollDataLoopThrottle, getDayRollDeclarationDetailsListThrottle } from '@src/spotZcqMarketPublic/dayRollMatch/dayRollTrade';
import { getCentralizedBiddingDataLoopThrottle } from '@src/spotZcqMarketPublic/monthConcentratedBidding';
import { getDeclarationLimitData } from '@src/spotZcqMarketPublic/declarationLimit';
import { getOpeningInformationDetailList } from '@src/spotZcqMarketPublic/monthConcentratedBidding'; 
import { DayRollSocketIntance } from "@src/spotZcqMarketPublic/dayRollMatch/dayRollSocket";
import { MALTPublicAccountList, dayRollSocketAccountList, getDeclarationLimitDataAccountList, getPriceAndQuantityAccountList, socketTradeAbleAccountList, zgpSocketAccountList } from '@src/config/business';
import { getAllZGBTradePlantDetail, getSaveBuyerPublicListAndDetailThrottle, getSaveSellerPublicListAndDetailThrottle } from '@src/spotZcqMarketPublic/zhaiGuaPai';
import { ZgpSocketIntance } from '@src/spotZcqMarketPublic/zhaiGuaPai/zgpSocket';

const MODE = import.meta.env.MODE
export const handleState = /^prod(.+)H$/.test(MODE)
export const devState = /^dev/.test(MODE)

// const everyReqIntervalSecond = 100 // 每个请求的间隔时间 /毫秒

/** 部分接口需要 机组id 参数 */
let unitid:string = ''

const setUinitId = (id?:string) => {
  if(!id) return 
  unitid = id
}

// /** 定时器 集合 */
// const allIntervalTimerList:Array<ReturnType<typeof setInterval>> = []
// /** 清除所有 interval */
// const clearAllInterval = () => {
//   allIntervalTimerList.forEach(val => clearInterval(val))
//   allIntervalTimerList.length = 0
// }

/** 创建所有类型的所有接口的定时请求的 记录timer */
const allTimeOutTimerList:Array<ReturnType<typeof setTimeout>> = []
/** 清除所有 timeOut */
const clearAllTimeOut = () => {
  allTimeOutTimerList.forEach(val => clearTimeout(val))
  allTimeOutTimerList.length = 0
}

/** 
 * 【现货市场】-【现货环境下中长期交易】-【电量信息详情查询】-【电量刻度信息详情查询】
 * 当月多品种
*/
const getMothTradeInfo = async ({headers, nowStr}:{headers:HeadersInit, nowStr:string}) => {
  console.log(
    `%c 【现货市场】-【现货环境下中长期交易】-【电量信息详情查询】-【电量刻度信息详情查询】 当月多品种`,
    'background:#35495e ; padding: 1px; border-radius: 3px 0 0 3px;  color: #fff',
  )

  if(!['12:00', '16:00'].includes(nowStr)) return Promise.resolve()

  await getSaveAllDayTradeInfo([], {headers, unitid})

  console.log('getMothTradeInfo 当月多品种 数据完成')
}


/** 
 * 【现货市场】-【现货环境下中长期交易】-【电量信息详情查询】-【电量刻度信息详情查询】
 * 下月至年底
*/
const getNextMonthToYearTradeInfo = async ({headers, nowStr}:{headers:HeadersInit, nowStr:string}) => {
  console.log(
    `%c 【现货市场】-【现货环境下中长期交易】-【电量信息详情查询】-【电量刻度信息详情查询】 下月至年底`,
    'background:#35495e ; padding: 1px; border-radius: 3px 0 0 3px;  color: #fff',
  )

  try {
    if(!['00:15'].includes(nowStr)) return Promise.resolve()
    
    const getDataDates = [26]
    const nextMonthToYear = [dayjs().add(1, 'month').startOf('month').format('YYYY-MM-DD'), dayjs().add(1, 'month').endOf('year').format('YYYY-MM-DD')]
    const dates = getDataDates.includes(dayjs().date()) ? nextMonthToYear : undefined
    
    await getSaveAllDayTradeInfo(dates, {headers, unitid}, true)
  
    console.log('getNextMonthToYearTradeInfo 下月至年底 数据完成')
  }catch(e) {
    console.error(e)
  }
}


type CreateAllImmediateReqParams = {headers:HeadersInit, id?:string}
type CreateAllImmediateReq = {(params:CreateAllImmediateReqParams):Promise<void>}
/**
 * 立即创建所有类型对应的所有的请求
 * @param headers 请求的headers
 */
export const createAllImmediateReq:CreateAllImmediateReq = async ({headers, id}) => {
  console.log(
    `%c createAllImmediateReq ${import.meta.env.VITE_APP_ENV}`,
    'background:#35495e ; padding: 1px; border-radius: 3px 0 0 3px;  color: #fff',
  )
  setUinitId(id)
  try {
    const nowStr = dayjs().format('HH:mm')

    // 每15分钟请求一次，使token不过期
    await getSaveOneTypeTradeInfo({headers, unitid, certainDate: '2024-01-01', jylx: 'ALL'})

    // 摘挂牌 每天更新三次场景列表；启动时更新一次
    if(['08:00', '12:00', '18:00'].includes(nowStr)) getAllZGBTradePlantDetail(headers)

      

    if(handleState) return

    // 【现货市场】- 【现货环境下中长期交易】- 【集中竞价交易申报】   开盘后数据暂时不用
    // await getAfterOpeningBellList({headers,unitid,nowStr})

    // 公有数据
    if(MALTPublicAccountList.includes(unitid)) {
      // 【现货市场】- 【现货环境下中长期交易】- 【集中竞价交易】- 【开盘信息查询】
      await getOpeningInformationDetailList({headers,unitid,nowStr}) 
    }

    // 私有数据
    if(getDeclarationLimitDataAccountList.includes(unitid)) {
      // 【现货市场】- 【现货环境下中长期交易】- （【申报额度管理】-【发电侧最新额度查询】 && 【电量限值管理】-【发电侧上限查询】）
      await getDeclarationLimitData({headers,unitid,nowStr})
    }

    // 私有数据
    if(getPriceAndQuantityAccountList.includes(unitid)) {
       // 【现货市场】-【现货环境下中长期交易】-【电量信息详情查询】-【电量刻度信息详情查询】当月多品种
       await getMothTradeInfo({headers, nowStr})
       // 【现货市场】-【现货环境下中长期交易】-【电量信息详情查询】-【电量刻度信息详情查询】下月至年底
       await getNextMonthToYearTradeInfo({headers, nowStr})
    }

  } catch(e) {
    console.error(e)
  }
}


/** 创建所有类型对应的所有的请求 的  请求间隔*/
const createAllIntervalReq = (headers:HeadersInit) => {
  // 距离下一个获取数据时刻的毫秒数
  const intervalActiontime = reqActionTime()

  console.log(
    `%c 当前时间: ${dayjs().format('YYYY-MM-DD HH:mm:ss')}`,
    'background:red ; padding: 1px; border-radius: 3px 0 0 3px;  color: black'
  )
  console.log(
    `%c 下一次获取数据时间: ${dayjs(new Date().getTime() + intervalActiontime).format('YYYY-MM-DD HH:mm:ss')}`,
    'background:pink ; padding: 1px; border-radius: 3px 0 0 3px;  color: black'
  )

  clearAllTimeOut()
  const timeOutTimer = setTimeout(() => {
    createAllImmediateReq({headers})
    createAllIntervalReq(headers)
  }, intervalActiontime)
  
  allTimeOutTimerList.push(timeOutTimer)
}


 /** 创建所有类型的所有接口的定时请求 */
 const createSpotMarketZcqAllReqLoop = (headers:HeadersInit, id?:string) => {
  console.log(
    `%c createSpotMarketZcqAllReqLoop ${import.meta.env.VITE_APP_ENV}`,
    'background:#35495e ; padding: 1px; border-radius: 3px 0 0 3px;  color: #fff',
  )
  setUinitId(id)

  createAllIntervalReq(headers)

  if(handleState) return

  // 公有数据
  if(MALTPublicAccountList.includes(unitid)) {
    createGetRollDataLoopThrottle({headers, unitid})

    getCentralizedBiddingDataLoopThrottle({headers, unitid})

    // 摘挂牌 每天更新三次场景列表；启动时更新一次
    getAllZGBTradePlantDetail(headers)
    getSaveBuyerPublicListAndDetailThrottle({headers,unitid, type:'buy'})
    getSaveSellerPublicListAndDetailThrottle({headers,unitid, type:'sell'})
  }

  // 在测试环境且能实际下单的账号
  if(devState && socketTradeAbleAccountList.includes(unitid)) return

  // 私有数据 日滚动socket
  if(dayRollSocketAccountList.includes(unitid)) {
    DayRollSocketIntance.initSocketThrottle()
    getDayRollDeclarationDetailsListThrottle({headers,unitid,isAuto:true})
  }
  // 私有数据 摘挂牌socket
  if(zgpSocketAccountList.includes(unitid)) {
    ZgpSocketIntance.initSocketThrottle()
  }
}

export const createSpotMarketZcqAllReqLoopThrottle = throttle(createSpotMarketZcqAllReqLoop, 5000, {trailing:true, leading: false})


